package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private  DistrictInfoService districtInfoService;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private RoomInfoService roomInfoService;
    @Override
    public void customSaveOrUpdate(ApartmentSubmitVo apartmentSubmitVo) {
        // 1.了解本次是跟新还是保存
        boolean isUpdate = apartmentSubmitVo.getId() != null;
        ProvinceInfo provinceInfo = provinceInfoService.getById(apartmentSubmitVo.getProvinceId());
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());
        CityInfo cityInfo = cityInfoService.getById(apartmentSubmitVo.getCityId());
        apartmentSubmitVo.setCityName(cityInfo.getName());
        DistrictInfo districtInfo = districtInfoService.getById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());
        saveOrUpdate(apartmentSubmitVo);
        Long apartmentId = apartmentSubmitVo.getId();

        // 2.如果是更新，先删除中间表（公寓标签，公寓配套，公寓杂费值，图片表）
        if (isUpdate){
            // 公寓配套中间表
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentId);
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
            // 公寓杂费中间表
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentId);
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
           // 公寓标签
            LambdaQueryWrapper<ApartmentLabel> appartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, apartmentId);
            apartmentLabelService.remove(appartmentLabelLambdaQueryWrapper);
            //公寓图片表 item_id 对应数据id item_type 表名是房间还是公寓
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, apartmentId);
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphInfoLambdaQueryWrapper);
        }
        // 3.保存数据
        // 3.1 添加主表数据
          /*
          save 方法合适吗 不合适 saveOrUpdate()
          传参 apartmentSubmitVo 合适吗 ？ 合适  有ApartmentInfo约束
           */
//        3.2 保存公寓配套中间表
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if(!CollectionUtils.isEmpty(facilityInfoIds)){
            List<ApartmentFacility> apartmentFacilities = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .facilityId(facilityInfoId)
                        .apartmentId(apartmentId).build();
                apartmentFacilities.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilities);
        }
        // 3.3 公寓标签
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if(!CollectionUtils.isEmpty(labelIds)){
            List<ApartmentLabel> apartmentLabels = new ArrayList<>(labelIds.size());
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(apartmentId)
                        .labelId(labelId)
                        .build();
                apartmentLabels.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabels);
        }
        // 3.4 公寓杂费中间表
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if(!CollectionUtils.isEmpty(feeValueIds)){
            List<ApartmentFeeValue> apartmentFeeValues = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(apartmentId)
                        .feeValueId(feeValueId)
                        .build();
                apartmentFeeValues.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValues);
        }
        // 3.5 公寓图片表
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)){
            List<GraphInfo> graphInfos = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = GraphInfo.builder()
                        .name(graphVo.getName())
                        .itemType(ItemType.APARTMENT)
                        .itemId(apartmentId)
                        .url(graphVo.getUrl())
                        .build();
                graphInfos.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfos);
        }

    }

    @Override
    public IPage<ApartmentItemVo> customPage(ApartmentQueryVo queryVo, IPage<ApartmentItemVo> page) {
        page = apartmentInfoMapper.customPageQuery(page,queryVo);
        return page;
    }

    @Override
    public ApartmentDetailVo customGetById(Long id) {
        // 1.查询id对应的公寓信息
        ApartmentInfo apartmentInfo = getById(id);
        // 2.根据公寓id查询对应的配套集合
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.customQueryListById(id);
       // 3.根据公寓id查询对应的标签
        List<LabelInfo> labelInfoList = labelInfoMapper.customQueryListById(id);
        // 4.根据公寓id查询对应图片集合
        List<GraphVo> graphInfoList = graphInfoMapper.customQueryListById(ItemType.APARTMENT,id);
        // 5.根据公寓id查询对应的杂费集合
       List<FeeValueVo> feeValueVoList = feeValueMapper.customQueryListById(id);
        // 6.将结果集合并到vo返回
        ApartmentDetailVo apartmentDetailVo = ApartmentDetailVo.builder()
                .facilityInfoList(facilityInfoList)
                .labelInfoList(labelInfoList)
                .graphVoList(graphInfoList)
                .feeValueVoList(feeValueVoList)
                .build();
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);
        return apartmentDetailVo;
    }

    @Override
    public void CustomRemoveById(Long id) {
        // 先查询公寓有没有房间
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(roomInfoLambdaQueryWrapper);
        if(count > 0){
            throw  new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        // 1.删除公寓信息
        removeById(id);
        // 2.删除四个关系表数据
        // 配套信息
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
        // 公寓标签
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
        // 图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);
        // 杂费
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);

    }
}




